package com.iteaj.network.server.component;

import com.iteaj.network.config.DeviceProperties;
import com.iteaj.network.message.UnParseBodyMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public abstract class SimpleChannelDecoderComponentAdapter<M extends UnParseBodyMessage> extends DeviceTcpDecoderComponent<M> {

    public SimpleChannelDecoderComponentAdapter(DeviceProperties deviceProperties) {
        super(deviceProperties);
    }

    @Override
    public SimpleChannelDecoderWrapper getMessageDecoder() {
        return new SimpleChannelDecoderWrapper();
    }

    /**
     * @see io.netty.channel.ChannelHandler.Sharable 如果是线程安全可以使用
     */
    protected class SimpleChannelDecoderWrapper extends SimpleChannelInboundHandler<ByteBuf> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            try {
                final M proxy = SimpleChannelDecoderComponentAdapter.this.proxy(ctx, msg);
                if(proxy != null) {
                    ctx.fireChannelRead(proxy);
                }
            } catch (Exception e) {
                ctx.fireExceptionCaught(e);
            }
        }
    }
}
